import time
import requests
from lxml import etree
import ddddocr

# count = 0
# DEBUG = False
# while True:
# 	count += 1
# 	print(f"正在进行第{count}次破解")
# 	res = requests.get("http://127.0.0.1:8000/captcha_show/")
# 	tree = etree.HTML(res.text)
# 	csrfmiddlewaretoken = tree.xpath('//input[@name="csrfmiddlewaretoken"]/@value')[0]
# 	print(csrfmiddlewaretoken)
#
# 	captcha_0 = tree.xpath('//input[@name="captcha_0"]/@value')[0]
# 	print(captcha_0)
#
# 	src = tree.xpath('//img[@class="captcha"]/@src')[0]
# 	print(src)
#
# 	img_res = requests.get(f"http://127.0.0.1:8000{src}")
#
#
# 	ocr = ddddocr.DdddOcr(show_ad=False)
# 	code = ocr.classification(img_res.content)
# 	print(code, )
#
# 	if DEBUG:
# 		with open(f"./codes/django_code_{code}.jpg", "wb") as f:
# 			f.write(img_res.content)
#
# 	res = requests.post("http://127.0.0.1:8000/captcha_show/", data={
# 		"csrfmiddlewaretoken": csrfmiddlewaretoken,
# 		"captcha_0": captcha_0,
# 		"captcha_1": f"{code}"
# 	}, cookies=res.cookies)
#
# 	if "破解成功" in res.text:
# 		break
#
# 	time.sleep(1)
#
# print(f"破解成功")




count = 0
DEBUG = False
while True:
	count += 1
	print(f"正在进行第{count}次破解")
	session = requests.Session()
	res = session.get("http://127.0.0.1:8000/captcha_show/")
	tree = etree.HTML(res.text)
	csrfmiddlewaretoken = tree.xpath('//input[@name="csrfmiddlewaretoken"]/@value')[0]
	print(csrfmiddlewaretoken)

	captcha_0 = tree.xpath('//input[@name="captcha_0"]/@value')[0]
	print(captcha_0)

	src = tree.xpath('//img[@class="captcha"]/@src')[0]
	print(src)

	img_res = requests.get(f"http://127.0.0.1:8000{src}")
	ocr = ddddocr.DdddOcr(show_ad=False)
	code = ocr.classification(img_res.content)
	print(code, )

	if DEBUG:
		with open(f"./codes/django_code_{code}.jpg", "wb") as f:
			f.write(img_res.content)

	res = session.post("http://127.0.0.1:8000/captcha_show/", data={
		"csrfmiddlewaretoken": csrfmiddlewaretoken,
		"captcha_0": captcha_0,
		"captcha_1": f"{code}"
	})

	if "破解成功" in res.text:
		print("cookies", res.cookies)
		break

	time.sleep(1)

print(f"破解成功")